package com.eco.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eco.bean.Projects;
import com.eco.bean.Users;
import com.eco.service.ProjectsService;

import com.eco.util.Result;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("projects")
@CrossOrigin
public class ProjectcController {
    @Autowired
    ProjectsService projectsService;

    @GetMapping("list")
    public Result getlist(){
        List<Projects> list = projectsService.list();
        return Result.success(list);
    }

    @PostMapping("/")
    public Result add(@RequestBody Projects projects){

        String name=projects.getProjectName();
        projects.setProjectName(name);
        projectsService.save(projects);
        Projects admin = projectsService.getById(projects.getProjectId());
        return Result.success("保存成功",admin);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") String id){
        boolean b=projectsService.removeById(id);
        if(b){
            return Result.success("删除成功",null);
        }
        else{
            return Result.fail(201,"删除失败");
        }
    }
    @PutMapping
    public Result edit(@RequestBody Projects projects){
        Boolean b=projectsService.saveOrUpdate(projects);
        Projects users1=projectsService.getById(projects.getProjectId());
        if (b){
            return Result.success("保存成功",users1);
        }
        else{
            return Result.fail(500,"保存失败");
        }
    }

    @GetMapping("page")
    public Result getPage(Page page, @RequestParam("searchText") String searchText) {
        IPage<Projects> result;

        if (searchText == null || searchText.isEmpty()) {
            result = projectsService.page(page);
        } else {
            QueryWrapper<Projects> wrapper = new QueryWrapper<Projects>();
            wrapper.like("project_name", searchText);

            result = projectsService.page(page, wrapper); // ✅ 使用 wrapper 查询
        }
        return Result.success(result);
    }
}
